// pages/index/activate/index.js
const app = getApp()
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		data: '',
		baseUrl: app.globalData.baseUrl,
		id: '',
		type: 1,
		role: 1,
		fapiao:'',
		arrImgs:[]
  },
  reApplyOrder(){

    wx.navigateTo({
      url: '/pages/apply/opera/index',
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
        acceptDataFromOpenedPage: function(data) {//参数名字随便起，前后页面对应上即可
        //对发送回来的数据进行处理
          console.log(data)
        },
        someEvent: (data)=> {//参数名字随便起，前后页面对应上即可
          console.log(data)
        }
      },
      success: (res)=> {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', { data: this.data.data })//参数名字随便起，前后页面对应上即可
      },
    })
  
  },
	onGetCocact(e) {
		let phone = e.currentTarget.dataset.phone;
		wx.makePhoneCall({
			phoneNumber: phone //仅为示例，并非真实的电话号码
		})
	},
	delImg(e) {
		let index = e.currentTarget.dataset.index;
		let arrs = this.data.arrImgs;
		arrs.splice(index, 1);
		this.setData({
			arrImgs: arrs
		})
  },
  previewPdf(e){
    let src=e.currentTarget.dataset.src;
    wx.downloadFile({
      // 示例 url，并非真实存在
      url: src,
      success: function (res) {
        const filePath = res.tempFilePath
        wx.openDocument({
          filePath: filePath,
          success: function (res) {
            console.log('打开文档成功')
          }
        })
      }
    })
  },
  
	onPreview(e){
    // var url =  e
   
    wx.previewImage({
      current: e.currentTarget.dataset.src, // 当前显示图片的 http 链接
      urls: [e.currentTarget.dataset.src] // 需要预览的图片 http 链接列表
    })
		
	},
	onUploadDingsun(file, type) {
		let that = this;
		wx.showLoading({
			title: '上传中',
			mask: true
		})
		var formData = {
			"module": "order",
			"imgIsCut": "false"
		}
		wx.uploadFile({
			url: app.globalData.baseUrl + '/guard/upload', //仅为示例，非真实的接口地址
			method: 'POST', //这句话好像可以不用
			header: {
				// 'content-type': 'multipart/form-data',
				"Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
				'token': app.globalData.token,
			},
			formData: formData,
			filePath: file[0].path,
			name: 'file',
			success(res) {
				wx.hideLoading()
				let data = JSON.parse(res.data)
				if (data.status) {
					that.setData({
						imgDingsun: data.data.records.filePath,
					})
				} else {
					wx.showToast({
						title: data.msg,
						icon: 'none',
						duration: 2000
					})
				}

				//do something
			}
		})
		return false;

	},
	onChoseImg() {
		var that = this;
		wx.chooseImage({
			count: 1,
			mediaType: ['image'],
			sourceType: ['album', 'camera'],
			maxDuration: 30,
			camera: 'back',
			success(res) {
				let size = res.tempFiles[0].size;
				if (size > 1024 * 1024 * 2) {
					wx.showToast({
						title: '文件过大',
						icon: 'none',
						duration: 2000
					})
					return false
				}
		
				that.onUploadDingsun(res.tempFiles, 'image')

			}
		})
	},
	onEndRepair() {
		let that = this;
		if (!that.data.imgDingsun) {
			wx.showToast({
				icon: 'none',
				title: '请先上传用户签字图片'
			})
			return false
		}
		if (that.data.arrImgs.length<=0) {
			wx.showToast({
				icon: 'none',
				title: '请先上传修复图片'
			})
			return false
		}
		wx.showModal({
			title: '提示',
			content: '是否确认提交？',
			confirmColor: '#DC5640',
			success(res) {
				if (res.confirm) {
					wx.showLoading({
						title: '加载中',
						mask: true
					})
					wx.request({
						url: app.globalData.baseUrl + '/api/myOrder/repaired',
						method: 'GET',
						header: {
							'content-type': 'application/x-www-form-urlencoded',
							'token': app.globalData.token,
						},
						data: {
							id: that.data.id,
							qianzi_url: that.data.imgDingsun,
							repaired_urls:that.data.arrImgs?that.data.arrImgs.join(',') : ''
						},
						success: function(res) {
							wx.hideLoading()
							if (res.data.status) {
								wx.showModal({
									title: "提示",
									content: '提交成功',
									icon: 'none',
									showCancel: false,
									confirmColor: '#DC5640',
									success(res) {
										wx.navigateBack()
									}
								})

							}else  {
								wx.showToast({
									icon: 'none',
									title: res.data.msg
								})
							}
						},
						fail: function() {
							wx.hideLoading()
							console.log("请求失败")
						}
					})
				}
			}
		})

	},
	onStartRepair() {
		let that = this;
		wx.showLoading({
			title: '加载中',
			mask: true
		})
		wx.request({
			url: app.globalData.baseUrl + '/api/myOrder/startRepair',
			method: 'GET',
			header: {
				'content-type': 'application/x-www-form-urlencoded',
				'token': app.globalData.token,
			},
			data: {
				id: that.data.id,
			},
			success: function(res) {
				wx.hideLoading()
				if (res.data.status) {
					wx.showModal({
						title: "提示",
						content: '提交成功',
						icon: 'none',
						showCancel: false,
						confirmColor: '#DC5640',
						success(res) {
							wx.navigateBack()
						}
					})

				}
			},
			fail: function() {
				wx.hideLoading()
				console.log("请求失败")
			}
		})
	},
	onJiedan() {
		let that = this;
		wx.showLoading({
			title: '加载中',
			mask: true
		})
		wx.request({
			url: app.globalData.baseUrl + '/api/myOrder/receiveOrder',
			method: 'GET',
			header: {
				'content-type': 'application/x-www-form-urlencoded',
				'token': app.globalData.token,
			},
			data: {
				id: that.data.id
			},
			success: function(res) {
				wx.hideLoading()
				if (res.data.status) {
					wx.showModal({
						title: "提示",
						content: '接单成功',
						icon: 'none',
						showCancel: false,
						confirmColor: '#DC5640',
						success(res) {
							wx.redirectTo({
								url: '/pages/order/index'
							})
						}
					})

				}
			},
			fail: function() {
				wx.hideLoading()
				console.log("请求失败")
			}
		})
	},
	onGetData(id) {
		let that = this;
		wx.showLoading({
			title: '加载中',
			mask: true
		})
		wx.request({
			url: app.globalData.baseUrl + '/api/myOrder/detail',
			method: 'GET',
			header: {
				'content-type': 'application/x-www-form-urlencoded',
				'token': app.globalData.token,
			},
			data: {
				id: id,
				type: app.globalData.role
			},
			success: function(res) {
				wx.hideLoading()
				if (res.data.status) {
					if (res.data.data.records.img_urls) {
						res.data.data.records.img_urls = res.data.data.records.img_urls.split(',')
					}
					if (res.data.data.records.repaired_urls) {
						res.data.data.records.repaired_urls = res.data.data.records.repaired_urls.split(',')
          }
          let suffix=res.data.data.records.ding_sun_url.split('.');
          suffix=suffix[suffix.length-1];
          
					that.setData({
            suffix:suffix,
						data: res.data.data.records,
						fapiao: res.data.data.records.invoice_url? res.data.data.records.invoice_url.split('/')[res.data.data.records.invoice_url.split('/').length-1]:''
					})

				}
			},
			fail: function() {
				wx.hideLoading()
				console.log("请求失败")
			}
		})
	},
	onGetCocact(e) {
		wx.makePhoneCall({
			phoneNumber:e.currentTarget.dataset.phone //仅为示例，并非真实的电话号码
		})
		
	},
	onUploadGuard(file, type) {
		let that = this;
		let formData = {}
		if (type == 1) {
			formData = {
				"module": "order",
				"imgIsCut": "false"
			}
		} else {
			formData = {
				"module": "order",
			}
		}
	
		wx.showLoading({
			title: '上传中',
			mask: true
		})
		wx.uploadFile({
			url: app.globalData.baseUrl + '/guard/upload', //仅为示例，非真实的接口地址
			method: 'POST', //这句话好像可以不用
			header: {
				'Content-Type': 'Application/x-www-form-urlencoded;charset=utf-8',
				'token': app.globalData.token,
			},
			filePath: file,
			name: 'file',
			formData: formData,
			success(res) {
				wx.hideLoading()
				let data = JSON.parse(res.data)
				if (data.status) {
					if (type == 1) {
						that.setData({
							imgXiaoan: data.data.records.filePath
						})
					} else {
						var arr = that.data.arrImgs;
						arr.push(data.data.records.filePath)
						that.setData({
							arrImgs: arr
						})
	
					}
	
				} else {
					wx.showToast({
						title: data.msg,
						icon: 'none',
						duration: 2000
					})
				}
	
				//do something
			}
		})
		return false;
	
	},
	choseImages() {
		let that = this;
		wx.chooseImage({
			count: 6,
			mediaType: ['image'],
			sourceType: ['album', 'camera'],
			maxDuration: 30,
			camera: 'back',
			success(res) {
	
				if (that.data.arrImgs.length + res.tempFiles.length > 6) {
					wx.showToast({
						title: "最多上传6张",
						icon: 'none',
						duration: 2000
					})
				} else {
					for (var i = 0; i < res.tempFiles.length; i++) {
						that.onUploadGuard(res.tempFiles[i].path, 2)
					}
	
				}
	
			}
		})
	},
	cancelOrder() {
		var that = this;
		wx.showLoading({
			title: '加载中',
			mask: true
		})
		wx.request({
			url: app.globalData.baseUrl + '/api/apply/cancel',
			method: 'GET',
			header: {
				'content-type': 'application/x-www-form-urlencoded',
				'token': app.globalData.token,
			},
			data: {
				order_id: that.data.id
			},
			success: function(res) {
				wx.hideLoading()
				if (res.data.status) {
					wx.showModal({
						title: "提示",
						content: '取消成功',
						icon: 'none',
						showCancel: false,
						confirmColor: '#DC5640',
						success(res) {
							wx.navigateBack()
						}
					})
				}
			},
			fail: function() {
				wx.hideLoading()
				console.log("请求失败")
			}
		})
	},
	onAgainApply() {
		var that = this;
		var arrImgs = that.data.data.img_urls;
		wx.showLoading({
			title: '提交中',
			mask: true
		})

		console.log(that.data.data)
		wx.request({
			url: app.globalData.baseUrl + '/api/apply/apply',
			method: 'POST',
			header: {
				'content-type': 'application/x-www-form-urlencoded',
				'token': app.globalData.token,
			},
			data: {
				"bao_xian_name": that.data.data.bao_xian_name,
				"chu_xian_date": that.data.data.chu_xian_date,
				"ding_sun_price": parseFloat(that.data.data.ding_sun_price),
				"car_number": that.data.data.car_number,
				"car_jia_number": that.data.data.car_jia_number,
				"case_number": that.data.data.case_number,
				"ding_sun_url": that.data.data.ding_sun_url,
				"cancel_case_url": that.data.data.cancel_case_url,
				"img_urls": arrImgs ? arrImgs.join(',') : ''
			},
			success: function(res) {
				wx.hideLoading()
				if (res.data.status) {
					wx.showModal({
						title: "提示",
						content: res.data.msg,
						icon: 'none',
						showCancel: false,
						confirmColor: '#DC5640',
						success(res) {
							wx.navigateBack()
						}
					})

				} else {
					wx.showToast({
						title: res.data.msg,
						icon: 'none',
						duration: 2000,
					})
				}
			},
			fail: function() {
				wx.hideLoading()
				console.log("请求失败")
			}
		})
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		if (app.globalData.role == 2) {
			this.setData({
				role: 2
			})
		}
		this.setData({
			id: options.id,
			type: options.type
		})
		
		this.onGetData(options.id)
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function(options) {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {

	}
})
